package cn.wolfcode.shop.cloud.web.controller;

import cn.wolfcode.shop.cloud.BusinessException;
import cn.wolfcode.shop.cloud.RedisService;
import cn.wolfcode.shop.cloud.Result;
import cn.wolfcode.shop.cloud.domain.OrderInfo;
import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.mq.OrderMessage;
import cn.wolfcode.shop.cloud.msg.SecKillCodeMsg;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISecKillGoodsService;
import cn.wolfcode.shop.cloud.service.ISecKillOrderService;
import cn.wolfcode.shop.cloud.util.SecKillKeyPrefix;
import cn.wolfcode.shop.cloud.util.UserAnnotation;
import cn.wolfcode.shop.cloud.vo.SecKillGoodVO;

import cn.wolfcode.shop.cloud.mq.MQConstans;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
public class SecKillOrderInfoController {

    @Autowired
    private ISecKillGoodsService secKillGoodsService;

    @Autowired
    private ISecKillOrderService secKillOrderService;

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    public static ConcurrentHashMap<Long, Boolean> fullSafeMap = new ConcurrentHashMap<>();

    @RequestMapping("/{path}/doSeckill")
    public Result doSeckill(Long seckillId, @PathVariable String path, @UserAnnotation User user, String uuid) {



        //判断是否登录
        if (user == null) {
            throw new BusinessException(SecKillCodeMsg.KILL_NOT_LOGIN);
        }


        //根据本地标识去进行判断 //商品已经被锁定 ？？有商品需要解锁
        Boolean flag = fullSafeMap.get(seckillId);
        if (flag != null && flag) {
            return Result.error(SecKillCodeMsg.KILL_OPT);
        }

//        //判断有没有数据
//        SecKillGoodVO secKillGoodVO = secKillGoodsService.find(seckillId);
//        if (secKillGoodVO == null) {
//            throw new BusinessException(SecKillCodeMsg.KILL_OPT);
//        }


        //2 根据订单id查询 数据,如果查询不到,非法操作
        SecKillGoodVO secKillGoodVO = secKillGoodsService.findByCache(seckillId);
        if(secKillGoodVO == null){
            return Result.error(SecKillCodeMsg.KILL_OPT);
        }

        //判断活动的时间
        Date now = new Date();
        if (now.getTime() < secKillGoodVO.getStartDate().getTime() || now.getTime() > secKillGoodVO.getEndDate().getTime()) {
            throw new BusinessException(SecKillCodeMsg.KILL_OPT);
        }

        //判断用户重复下单

//        SecKillOrder secKillOrder = secKillOrderService.queryByUserIdAndSeckillId(user.getId(), secKillGoodVO.getId());
//        if (secKillOrder != null) {
//            throw new BusinessException(SecKillCodeMsg.KILL_REPEAT);
//        }
        if (redisService.exists(SecKillKeyPrefix.SECKILL_ORDER,user.getId()+":"+seckillId)){
            throw new BusinessException(SecKillCodeMsg.KILL_REPEAT);
        }




        //判断库存
        if (secKillGoodVO.getStockCount() <= 0) {
            throw new BusinessException(SecKillCodeMsg.KILL_STOCK_OVER);
        }


        long count = redisService.decr(SecKillKeyPrefix.SECKILL_STOCK, seckillId + "");
        if (count < 0) {
            fullSafeMap.put(seckillId, true); //没有了 每个商品都有单独的库存数
            return Result.error(SecKillCodeMsg.KILL_STOCK_OVER);
        }


        //开始订单编号
        //String order_num = orderInfoService.seckill(user.getId(), secKillGoodVO.getId());

        //发送MQ


        //发送消息
        OrderMessage orderMessage = new OrderMessage();
        orderMessage.setSeckillId(seckillId);
        orderMessage.setUserId(user.getId());
        orderMessage.setUuid(uuid);
        rocketMQTemplate.syncSend(MQConstans.CREATE_ORDER_DEST, orderMessage);
        return Result.success("正在抢购中.. 请等待结果");
    }

    @RequestMapping("/queryByOrderNo")
    public Result queryByOrderNo(String orderNo, @UserAnnotation User user) {
        //判断是否登录
        if (user == null) {
            throw new BusinessException(SecKillCodeMsg.KILL_NOT_LOGIN);
        }

        OrderInfo orderInfo = orderInfoService.find(orderNo);
        if (orderInfo == null) {
            throw new BusinessException(SecKillCodeMsg.KILL_OPT);
        }

        //只能看自己的
        if (!orderInfo.getUserId().equals(user.getId())) {
            throw new BusinessException(SecKillCodeMsg.KILL_OPT);
        }

        return Result.success(orderInfo);

    }


}
